package net.cmkj.mine.core.admin.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Inject;

import net.cmkj.mine.bean.SysDept;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.common.anno.RequiresPermissions;
import net.cmkj.mine.common.controller.BaseController;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.CookieUtils;
import net.cmkj.mine.util.IWebUtils;
import net.cmkj.mine.util.MyDigestUtils;

public class MainController extends BaseController {
	
	//private MainService service = MainService.service;
	
	@Inject
	private MainService service;
	
	@RequiresPermissions(value= {"/main"})
	public void index() {
		SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
		String deptids = sysUser.getDeptids();
		if (deptids != null && !"".equals(deptids)) {
			String[] dids = deptids.split(",");
			List<SysDept> depts = new ArrayList<>();
			for (String deptId : dids) {
				SysDept dept = SysDept.dao.findById(deptId);
				depts.add(dept);
			}
			setAttr("selectDept", CookieUtils.getCookieByName(getRequest(), "user_dept"));
			setAttr("depts", depts);
		}
		render("main.html");
	}
	
	@RequiresPermissions(value= {"/main"})
	public void welcome() {
		render("welcome.html");
	}
	
	@RequiresPermissions(value= {"/main"})
	public void self() {
		render("self.html");
	}
	
	@RequiresPermissions(value= {"/main"})
	public void rePwd() {
		render("rePwd.html");
	}
	
	@RequiresPermissions(value= {"/main"})
	public void updPwd() {
		String oldPwd = getPara("oldPwd");
		String newPwd = getPara("newPwd");
		String pwdRepeat = getPara("pwdRepeat");
		SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
		if (!sysUser.getPwd().equals(MyDigestUtils.hash(MyDigestUtils.hash(oldPwd)))) {
			renderJson(InvokeResult.failure("旧密码不正确！"));
		} else {
			if (newPwd.equals(pwdRepeat)) {
				InvokeResult result = SysUser.dao.savePwdUpdate(sysUser.getId(), MyDigestUtils.hash(MyDigestUtils.hash(newPwd)));
				renderJson(result);
			} else { 
				renderJson(InvokeResult.failure("两次密码不一致"));
			}
		}
	}
	
	@RequiresPermissions(value= {"/main"})
	public void getWindowsInfo() {
		Map<String, Object> map = new HashMap<String, Object>();
		//WindowsInfoUtil wiu = new WindowsInfoUtil();
		//map.put("cpu", wiu.getCpuRatioForWindows());
		//map.put("ram", wiu.getMemery());
		renderJson(map);
	}

	@RequiresPermissions(value= {"/main"})
	public void changeDept() {
		String deptId = getPara("deptId");
		CookieUtils.addCookie(getResponse(), "user_dept", deptId, 60*60*24*30);
		SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
		sysUser.setDeptid(CommonUtils.converInteger(deptId));
		IWebUtils.setCurrentLoginSysUserToSession(getSession(), sysUser);
		renderJson(InvokeResult.success());
	}

}
